package cn.uikit.demo.location

import android.Manifest
import android.content.Context
import android.content.Intent
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.core.location.LocationManagerCompat
import androidx.lifecycle.lifecycleScope
import cn.uikit.demo.databinding.ActivityLocationTestBinding
import kotlinx.coroutines.launch
import sivin.uikit.extend.setOnSafeClickListener
import sivin.uikit.framework.BindingActivity
import sivin.uikit.framework.PermissionManager

class LocationTestActivity : BindingActivity<ActivityLocationTestBinding>(
    ActivityLocationTestBinding::inflate
) {

    companion object {
        fun launch(context: Context) {
            val startIntent = Intent(context, LocationTestActivity::class.java)
            context.startActivity(startIntent)
        }
    }

    private val permissionManager = PermissionManager(this)

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onViewCreate(savedInstanceState: Bundle?) {
        super.onViewCreate(savedInstanceState)

        binding.startBtn.setOnSafeClickListener {
            startLocationService()
        }
    }


    private fun startLocationService() {
        lifecycleScope.launch {
            val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                arrayOf(
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.POST_NOTIFICATIONS
                )
            } else {
                arrayOf(
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                )
            }
            val deniedList = permissionManager.checkAndRequest(permissions)
            if (deniedList.isEmpty()) {
                //申请是否允许在后台定位权限
                //不能将这个权限放到上面的array中一起申请，如果放到一起，则申请时不会弹出任何权限框，直接拒绝所有权限
                //因为是否允许后台定位权限的前提是，允许了定位权限
                permissionManager.checkAndRequest(arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION))
                startForegroundService()
            } else {
                //处理拒绝的权限
            }
        }
    }


    private fun startForegroundService() {
        val locationManager = getSystemService(LocationManager::class.java)
        if (!LocationManagerCompat.hasProvider(locationManager, LocationManager.GPS_PROVIDER)) {
            return
        }
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            return
        }
        //启动定位服务
        val intent = Intent(mActivity, LocationService::class.java)
        // Android8 必须通过startForegroundService开启前台服务，Android9 需要添加权限
        startForegroundService(intent)
    }


}